<template>
  <div class="statistics-dashboard">
    <!-- 数据概览卡片区域 -->
    <el-card class="overview-card" :body-style="{ padding: '15px' }">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
        "
      >
        <h2 class="section-title">📊 数据概览</h2>
        <el-button type="primary" @click="handleRefresh">刷新</el-button>
      </div>
      <div class="overview-container">
        <StatisticCard
          label="总告警数量"
          :value="overview.totalAlerts.toString()"
          :trend="overview.alertsTrend"
          :trend-percent="overview.alertsPercent"
          icon="el-icon-bell"
          type="primary"
        />
        <StatisticCard
          label="总工单数量"
          :value="overview.totalWorkorders.toString()"
          :trend="overview.workordersTrend"
          :trend-percent="overview.workordersPercent"
          icon="el-icon-document"
          type="success"
        />
        <StatisticCard
          label="部门数量"
          :value="overview.departmentCount.toString()"
          icon="el-icon-office-building"
          type="info"
        />
        <StatisticCard
          label="平均响应"
          :value="overview.averageResponse"
          :trend="overview.responseTrend"
          :trend-percent="overview.responsePercent"
          icon="el-icon-clock"
          type="warning"
        />
      </div>
    </el-card>

    <!-- 系统调度状态 -->
    <el-card class="schedule-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">🔄 系统调度状态</h2>
      <div class="schedule-container">
        <div class="schedule-item">
          <h3 class="schedule-title">告警检测调度</h3>
          <div class="schedule-status">
            <span class="status-dot running"></span>
            <span class="status-text">运行中</span>
          </div>
          <div class="schedule-next">
            下次执行: {{ schedule.alertNextTime }}
          </div>
          <el-button
            type="text"
            icon="el-icon-play"
            @click="handleRunNow('alert')"
            class="run-now-btn"
          >
            立即执行
          </el-button>
        </div>
        <div class="schedule-item">
          <h3 class="schedule-title">情报同步调度</h3>
          <div class="schedule-status">
            <span class="status-dot running"></span>
            <span class="status-text">运行中</span>
          </div>
          <div class="schedule-next">
            下次执行: {{ schedule.intelNextTime }}
          </div>
          <el-button
            type="text"
            icon="el-icon-play"
            @click="handleRunNow('intel')"
            class="run-now-btn"
          >
            立即执行
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 部门排名区域 -->
    <el-card class="ranking-card" :body-style="{ padding: '15px' }">
      <div class="ranking-header">
        <h2 class="section-title">📊 部门排名</h2>
        <el-select
          v-model="rankingTimeRange"
          @change="handleRankingTimeChange"
          size="small"
          class="time-range-select"
        >
          <el-option label="7天" value="7" />
          <el-option label="30天" value="30" />
          <el-option label="90天" value="90" />
          <el-option label="全年" value="365" />
        </el-select>
      </div>

      <el-tabs
        v-model="activeRankingTab"
        @tab-change="handleRankingTabChange"
        class="ranking-tabs"
      >
        <el-tab-pane label="综合评分" name="score" />
        <el-tab-pane label="告警数量" name="alerts" />
        <el-tab-pane label="响应速度" name="response" />
        <el-tab-pane label="解决率" name="solveRate" />
      </el-tabs>

      <el-table
        :data="departmentRanking"
        border
        class="ranking-table"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          label="排名"
          align="center"
          :formatter="formatRank"
          width="100"
        />
        <el-table-column label="部门" prop="department" />
        <el-table-column
          label="得分"
          prop="score"
          align="center"
          v-if="activeRankingTab === 'score'"
        />
        <el-table-column
          label="告警数"
          prop="alertCount"
          align="center"
          v-if="activeRankingTab === 'alerts'"
        />
        <el-table-column
          label="平均响应(小时)"
          prop="avgResponse"
          align="center"
          v-if="activeRankingTab === 'response'"
        />
        <el-table-column
          label="解决率"
          prop="solveRate"
          align="center"
          v-if="activeRankingTab === 'solveRate'"
        />
        <el-table-column
          label="工单数"
          prop="workorderCount"
          width="100"
          align="center"
        />
        <el-table-column
          label="趋势"
          width="80"
          align="center"
          :formatter="formatTrend"
        />
      </el-table>
    </el-card>

    <!-- 图表区域 -->
    <div class="charts-row">
      <!-- 工单状态分布 -->
      <el-card class="chart-card left-chart">
        <h2 class="section-title">📈 工单状态分布</h2>
        <div class="chart-container">
          <div ref="workorderChartRef" class="chart" />
          <div class="chart-legend">
            <div
              v-for="(item, index) in workorderStatusData"
              :key="index"
              class="legend-item"
            >
              <span
                :style="{ backgroundColor: workorderColors[index] }"
                class="legend-color"
              ></span>
              <span class="legend-text">{{ item.name }}: {{ item.value }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 告警风险等级分布 -->
      <el-card class="chart-card right-chart">
        <h2 class="section-title">📈 告警风险等级分布</h2>
        <div class="chart-container">
          <div ref="riskLevelChartRef" class="chart" />
          <div class="chart-legend">
            <div
              v-for="(item, index) in riskLevelData"
              :key="index"
              class="legend-item"
            >
              <span
                :style="{ backgroundColor: riskLevelColors[index] }"
                class="legend-color"
              ></span>
              <span class="legend-text">{{ item.name }}: {{ item.value }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 趋势分析区域 -->
    <el-card class="trend-card" :body-style="{ padding: '15px' }">
      <div class="trend-header">
        <h2 class="section-title">📈 趋势分析</h2>
        <el-select
          v-model="trendTimeRange"
          @change="handleTrendTimeChange"
          size="small"
          class="time-range-select"
        >
          <el-option label="最近7天" value="7" />
          <el-option label="最近30天" value="30" />
          <el-option label="最近90天" value="90" />
          <el-option label="今年" value="year" />
        </el-select>
      </div>
      <div ref="trendChartRef" class="trend-chart-container" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch, nextTick } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import * as echarts from "echarts";
import type { ECharts } from "echarts";
import StatisticCard from "./AlarmCenter/components/StatisticCard.vue";

// 模拟API导入（实际项目中替换为真实接口）
import {
  getOverviewData,
  getScheduleStatus,
  getDepartmentRanking,
  getWorkorderStatusData,
  getRiskLevelData,
  getTrendData,
  runScheduleTask,
  getWorkorderStatistics,
  getAlertStatistics,
} from "../servers";

// 页面状态
const username = ref("张三");
const refreshLoading = ref(false);
const activeRankingTab = ref("score");
const rankingTimeRange = ref("30");
const trendTimeRange = ref("30");

// 概览数据
const overview = reactive({
  totalAlerts: 237,
  alertsTrend: "up", // up/down
  alertsPercent: 12,
  totalWorkorders: 16,
  workordersTrend: "down",
  workordersPercent: 5,
  departmentCount: 7,
  averageResponse: "2.5小时",
  responseTrend: "down",
  responsePercent: 15,
});

// 调度状态
const schedule = reactive({
  alertStatus: "running",
  alertNextTime: "15:00",
  intelStatus: "running",
  intelNextTime: "16:00",
});

// 部门排名数据
const departmentRanking = ref([
  {
    department: "安全部",
    score: 99.2,
    alertCount: 8,
    workorderCount: 2,
    solveRate: "100%",
    avgResponse: 1.2,
    trend: "up",
  },
  {
    department: "运维部",
    score: 79.4,
    alertCount: 15,
    workorderCount: 6,
    solveRate: "67%",
    avgResponse: 2.8,
    trend: "same",
  },
  {
    department: "测试部",
    score: 69.2,
    alertCount: 10,
    workorderCount: 8,
    solveRate: "50%",
    avgResponse: 3.5,
    trend: "down",
  },
  {
    department: "研发部",
    score: 65.0,
    alertCount: 0,
    workorderCount: 0,
    solveRate: "-",
    avgResponse: 0,
    trend: "up",
  },
  {
    department: "产品部",
    score: 64.0,
    alertCount: 0,
    workorderCount: 0,
    solveRate: "-",
    avgResponse: 0,
    trend: "same",
  },
  {
    department: "市场部",
    score: 63.0,
    alertCount: 0,
    workorderCount: 0,
    solveRate: "-",
    avgResponse: 0,
    trend: "down",
  },
  {
    department: "财务部",
    score: 59.0,
    alertCount: 0,
    workorderCount: 0,
    solveRate: "-",
    avgResponse: 0,
    trend: "same",
  },
]);

// 工单状态数据
const workorderStatusData = ref([
  { name: "已解决", value: 4 },
  { name: "处理中", value: 2 },
  { name: "待审核", value: 6 },
  { name: "已拒绝", value: 2 },
  { name: "待处理", value: 2 },
]);

const workorderColors = ["#52c41a", "#faad14", "#1890ff", "#f5222d", "#722ed1"];

// 风险等级数据
const riskLevelData = ref([
  { name: "严重", value: 5 },
  { name: "高", value: 8 },
  { name: "中", value: 12 },
  { name: "低", value: 8 },
]);

const riskLevelColors = ["#f5222d", "#faad14", "#1890ff", "#52c41a"];

// 趋势数据
const trendData = ref({
  dates: [],
  alertCounts: [],
});

// 图表引用
const workorderChartRef = ref<HTMLDivElement>(null);
const riskLevelChartRef = ref<HTMLDivElement>(null);
const trendChartRef = ref<HTMLDivElement>(null);

// 图表实例
let workorderChart: ECharts | null = null;
let riskLevelChart: ECharts | null = null;
let trendChart: ECharts | null = null;

// 初始化图表
const initCharts = () => {
  // 工单状态分布图表
  if (workorderChartRef.value) {
    workorderChart = echarts.init(workorderChartRef.value);
    updateWorkorderChart();
  }

  // 风险等级分布图表
  if (riskLevelChartRef.value) {
    riskLevelChart = echarts.init(riskLevelChartRef.value);
    updateRiskLevelChart();
  }

  // 趋势分析图表
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value);
    updateTrendChart();
  }

  // 监听窗口大小变化，调整图表尺寸
  window.addEventListener("resize", handleResize);
};

// 处理窗口大小变化
const handleResize = () => {
  workorderChart?.resize();
  riskLevelChart?.resize();
  trendChart?.resize();
};

// 更新工单状态图表
const updateWorkorderChart = () => {
  if (!workorderChart) return;

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    series: [
      {
        name: "工单状态",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: workorderStatusData.value,
        color: workorderColors,
      },
    ],
  };

  workorderChart.setOption(option);
};

// 更新风险等级图表
const updateRiskLevelChart = () => {
  if (!riskLevelChart) return;

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    series: [
      {
        name: "风险等级",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: riskLevelData.value,
        color: riskLevelColors,
      },
    ],
  };

  riskLevelChart.setOption(option);
};

// 更新趋势图表
const updateTrendChart = () => {
  if (!trendChart) return;

  // 如果没有数据，生成模拟数据
  if (trendData.value.dates.length === 0) {
    const days = parseInt(trendTimeRange.value) || 30;
    const dates = [];
    const counts = [];

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
      counts.push(Math.floor(Math.random() * 20) + 5);
    }

    trendData.value = { dates, alertCounts: counts };
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        data: trendData.value.dates,
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "告警数量",
        min: 0,
        interval: 5,
        axisLabel: {
          formatter: "{value}",
        },
      },
    ],
    series: [
      {
        name: "告警数量",
        type: "line",
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        data: trendData.value.alertCounts,
        lineStyle: {
          width: 3,
          color: "#1890ff",
        },
        itemStyle: {
          color: "#1890ff",
          borderColor: "#fff",
          borderWidth: 2,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(24, 144, 255, 0.3)" },
            { offset: 1, color: "rgba(24, 144, 255, 0)" },
          ]),
        },
      },
    ],
  };

  trendChart.setOption(option);
};

// 格式化排名
const formatRank = (row: any, column: any, value: any, index: number) => {
  const rank = index + 1;
  if (rank === 1) return "🥇";
  if (rank === 2) return "🥈";
  if (rank === 3) return "🥉";
  return String(rank);
};

// 格式化趋势
const formatTrend = (row: any, column: any, value: any) => {
  if (row.trend === "up") return "↑";
  if (row.trend === "down") return "↓";
  return "→";
};

// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (rowIndex < 3) {
    return "top-ranking";
  }
  return "";
};

// 获取概览数据
const fetchOverviewData = async () => {
  try {
    // 如果后端有概览接口，直接调用
    try {
      const { data } = await getOverviewData();
      if (data) {
        Object.assign(overview, data);
        return;
      }
    } catch (e) {
      // 如果概览接口不存在，组合工单和告警统计
    }

    // 组合工单和告警统计数据
    const [workorderResult, alertResult] = await Promise.all([
      getWorkorderStatistics().catch(() => null),
      getAlertStatistics().catch(() => null),
    ]);

    if (workorderResult?.data) {
      overview.totalWorkorders = workorderResult.data.total_count || 0;
    }

    if (alertResult?.data) {
      overview.totalAlerts = alertResult.data.total_count || 0;
    }
  } catch (error: any) {
    console.error("获取概览数据失败:", error);
  }
};

// 计算告警检测调度的下次执行时间
const getNextAlertScheduleTime = (): string => {
  const now = new Date();
  const nextRun = new Date(now);
  nextRun.setHours(now.getHours() + 1, 0, 0, 0);
  return nextRun.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 获取调度状态
const fetchScheduleStatus = async () => {
  try {
    // 获取情报调度状态
    const { data } = await getScheduleStatus();
    if (data) {
      // 处理情报调度状态
      if (data.jobs && data.jobs.length > 0) {
        const nextJob = data.jobs[0];
        schedule.intelNextTime = nextJob.next_run_time
          ? new Date(nextJob.next_run_time).toLocaleString("zh-CN", {
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit",
            })
          : "未知";
        schedule.intelStatus = data.scheduler_running ? "running" : "stopped";
      }
    }

    // 告警检测调度（前端计算）
    schedule.alertStatus = "running";
    schedule.alertNextTime = getNextAlertScheduleTime();
  } catch (error: any) {
    console.error("获取调度状态失败:", error);
    // 如果接口失败，使用默认值
    schedule.alertStatus = "running";
    schedule.alertNextTime = getNextAlertScheduleTime();
  }
};

// 获取部门排名
const fetchDepartmentRanking = async () => {
  try {
    const { data } = await getDepartmentRanking({
      days: rankingTimeRange.value,
      type: activeRankingTab.value,
    });
    if (data?.rankings) {
      // 处理返回的排名数据格式
      departmentRanking.value = data.rankings.map((item: any) => ({
        department: item.department,
        score: item.score,
        alertCount: item.alert_count,
        workorderCount: item.ticket_count,
        solveRate:
          item.resolution_rate !== undefined
            ? `${item.resolution_rate.toFixed(0)}%`
            : "-",
        avgResponse: item.avg_response_hours || 0,
        trend: item.trend || "same",
      }));
    }
  } catch (error: any) {
    console.error("获取部门排名失败:", error);
  }
};

// 获取工单状态数据
const fetchWorkorderStatusData = async () => {
  try {
    const data = await getWorkorderStatusData();
    if (data && Array.isArray(data)) {
      workorderStatusData.value = data;
      updateWorkorderChart();
    }
  } catch (error: any) {
    console.error("获取工单状态数据失败:", error);
  }
};

// 获取风险等级数据
const fetchRiskLevelData = async () => {
  try {
    const data = await getRiskLevelData();
    if (data && Array.isArray(data)) {
      riskLevelData.value = data;
      updateRiskLevelChart();
    }
  } catch (error: any) {
    console.error("获取风险等级数据失败:", error);
  }
};

// 获取趋势数据
const fetchTrendData = async () => {
  try {
    const result = await getTrendData({
      range: trendTimeRange.value,
    });

    // 如果后端返回趋势数据，直接使用
    if (result?.data?.dates && result?.data?.alertCounts) {
      trendData.value = {
        dates: result.data.dates,
        alertCounts: result.data.alertCounts,
      };
      updateTrendChart();
      return;
    }

    // 如果没有趋势数据，生成模拟数据（保持原有逻辑）
    const days =
      trendTimeRange.value === "year"
        ? 365
        : parseInt(trendTimeRange.value as string) || 30;
    const dates = [];
    const counts = [];

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
      counts.push(Math.floor(Math.random() * 20) + 5);
    }

    trendData.value = { dates, alertCounts: counts };
    updateTrendChart();
  } catch (error: any) {
    console.error("获取趋势数据失败:", error);
  }
};

// 刷新所有数据
const refreshAllData = async () => {
  refreshLoading.value = true;
  try {
    await Promise.all([
      fetchOverviewData(),
      fetchScheduleStatus(),
      fetchDepartmentRanking(),
      fetchWorkorderStatusData(),
      fetchRiskLevelData(),
      fetchTrendData(),
    ]);
    ElMessage.success("数据刷新成功");
  } catch (error) {
    ElMessage.error("数据刷新失败");
  } finally {
    refreshLoading.value = false;
  }
};

// 处理手动刷新
const handleRefresh = () => {
  refreshAllData();
};

// 处理排名Tab切换
const handleRankingTabChange = () => {
  fetchDepartmentRanking();
};

// 处理排名时间范围变化
const handleRankingTimeChange = () => {
  fetchDepartmentRanking();
};

// 处理趋势时间范围变化
const handleTrendTimeChange = () => {
  fetchTrendData();
};

// 处理立即执行调度任务
const handleRunNow = async (type: string) => {
  try {
    if (type === "alert") {
      ElMessage.warning("告警检测调度暂不支持手动触发");
      return;
    }

    const result = await runScheduleTask(type as "alert" | "intel");
    ElNotification({
      title: "成功",
      message: `情报同步任务已开始执行`,
      type: "success",
    });

    // 刷新调度状态
    fetchScheduleStatus();
  } catch (error: any) {
    ElMessage.error(error?.message || "执行任务失败");
  }
};

// 设置定时刷新
const setupAutoRefresh = () => {
  // 每5分钟自动刷新一次
  setInterval(refreshAllData, 5 * 60 * 1000);
};

// 初始化
onMounted(() => {
  // 初始化数据
  refreshAllData();

  // 初始化图表
  nextTick(() => {
    initCharts();
  });

  // 设置自动刷新
  setupAutoRefresh();
});

// 监听数据变化，更新图表
watch(workorderStatusData, updateWorkorderChart);
watch(riskLevelData, updateRiskLevelChart);
watch(trendData, updateTrendChart);

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  workorderChart?.dispose();
  riskLevelChart?.dispose();
  trendChart?.dispose();
});
</script>

<style scoped lang="scss">
.statistics-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .navbar-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .navbar-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #333;
      }

      .user-info {
        color: #666;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 10px;

        .refresh-btn {
          padding: 0 5px;
        }
      }
    }
  }

  .overview-card,
  .schedule-card,
  .ranking-card,
  .chart-card,
  .trend-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .overview-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .schedule-container {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    padding: 10px 0;

    .schedule-item {
      flex: 1;
      min-width: 250px;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 8px;
      position: relative;

      .schedule-title {
        font-size: 14px;
        color: #666;
        margin: 0 0 10px 0;
      }

      .schedule-status {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 10px;

        .status-dot {
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
        }

        .status-dot.running {
          background-color: #52c41a;
        }

        .status-dot.stopped {
          background-color: #f5222d;
        }

        .status-text {
          font-size: 14px;
          font-weight: 500;
        }
      }

      .schedule-next {
        font-size: 13px;
        color: #666;
        margin-bottom: 10px;
      }

      .run-now-btn {
        position: absolute;
        right: 15px;
        top: 15px;
        padding: 0 5px;
        color: #1890ff;
      }
    }
  }

  .ranking-header,
  .trend-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .time-range-select {
      width: 120px;
    }
  }

  .ranking-tabs {
    margin-bottom: 15px;
  }

  .ranking-table {
    width: 100%;

    .top-ranking {
      background-color: rgba(250, 240, 230, 0.3);
    }
  }

  .charts-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    @media (max-width: 992px) {
      flex-direction: column;
    }
  }

  .chart-card {
    flex: 1;
    min-width: 300px;

    .chart-container {
      position: relative;
      height: 300px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .chart {
      width: 100%;
      height: 220px;
    }

    .chart-legend {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 15px;
      margin-top: 10px;
      width: 100%;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 12px;

        .legend-color {
          width: 12px;
          height: 12px;
          border-radius: 3px;
          display: inline-block;
        }
      }
    }
  }

  .trend-chart-container {
    width: 100%;
    height: 350px;
  }

  // 响应式调整
  @media (max-width: 768px) {
    .overview-container {
      flex-direction: column;
    }

    .schedule-container {
      flex-direction: column;
    }

    .chart-card {
      width: 100%;
    }
  }
}
</style>
